/*
 * Copyright (c) 2001-2023 cnstrong.cn Corporation Limited. All rights reserved.
 * This software is the confidential and proprietary information of cnstrong.cn Company.
 * ("Confidential Information").
 * You shall not disclose such Confidential Information and shall use it only
 * in accordance with the terms of the license agreement you entered into with cnstrong.cn.
 */
package com.tree.config.impl;

import com.alibaba.fastjson.JSON;
import com.tree.config.ConfigTreeService;
import com.tree.config.annotation.CfgBeanCode;
import com.tree.config.base.WeTreeConstants;
import com.tree.config.exception.WeTreeException;
import com.tree.config.repository.WeTreeRepository;

import java.util.Optional;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import lombok.extern.slf4j.Slf4j;

/**
 * ConfigTreeServiceImpl
 *
 * @author Braveheart
 * @version V1.0
 * @since 2023-12-28
 */
@Slf4j
@Component
public class ConfigTreeServiceImpl implements ConfigTreeService {

    @Resource
    private WeTreeRepository weTreeRepository;

    @Override
    public <T> Optional<T> get(Object bizId, Class<T> clz) {
        try {
            // 查询注解
            Optional<CfgBeanCode> optionalCfgBeanCode = getCfgBeanCode(clz);

            // 获取注解属性
            String projectCode = optionalCfgBeanCode.map(CfgBeanCode::projectCode).orElse(null);
            String parentCode = optionalCfgBeanCode.map(CfgBeanCode::parentCode).orElse(null);
            String currCode = optionalCfgBeanCode.map(CfgBeanCode::currCode).orElse(null);

            Assert.notNull(projectCode, "工程名为空");
            Assert.notNull(parentCode, "父级配置编码为空");
            Assert.notNull(currCode, "当前配置编码为空");

            // 查询配置数据（JSON格式）
            String jsonResult = weTreeRepository.getDictCommon(projectCode, parentCode, currCode, bizId);
            if (StringUtils.isBlank(jsonResult) || StringUtils.equals(WeTreeConstants.CODIS_VALUE_PIERCE_THROUGH, jsonResult)) {
                return Optional.empty();
            }
            // 数据反射解析成对象
            T t = JSON.parseObject(jsonResult, clz);

            return Optional.ofNullable(t);

        } catch (Exception e) {
            log.error("查询字典配置异常, bizId={}, class={}", bizId, clz, e);
            throw new WeTreeException(e);
        }
    }

    /**
     * 获取类的注解
     *
     * @param clz
     * @param <T>
     * @return
     */
    private <T> Optional<CfgBeanCode> getCfgBeanCode(Class<T> clz) {
        CfgBeanCode cfgBeanCode = clz.getDeclaredAnnotation(CfgBeanCode.class);
        return Optional.ofNullable(cfgBeanCode);
    }
}
